/*
 * @Author: revol
 * @Date: 2022-07-28 14:39:29
 * @LastEditors: revol
 * @LastEditTime: 2022-07-28 14:46:40
 * @Description: 获取可用端口，参考自 唐霜大佬
 */

const net = require('net')

// 检查端口是否可用
function checkPortUsable(port) {
    return new Promise((resolve, reject) => {
        const server = net.createConnection({ port })
        /**1. 如果触发connect钩子则表示当前端口正在使用，reject
         * 2. 如果触发error钩子则表示当前端口可以使用，resolve
         *  */
        server.on('connect', () => {
            server.end()
            reject(`Port ${port} is not available!`)
        })
        server.on('error', () => {
            resolve(port)
        })
    })
}

// 根据给定范围随机生成端口值
function randomNumByRange(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min
}

// 查询可用端口
function findUsablePort(port, minPort = 10000, maxPort = 65536) {
    const retry = () => {
        const port = randomNumByRange(minPort, maxPort)
        return findUsablePort(port, minPort, maxPort)
    }
    return checkPortUsable(port)
        .then(() => port)
        .catch(retry)
}

module.exports = {
    findUsablePort,
    checkPortUsable
}
